package com.qf.web.controller;

import cn.dsna.util.images.ValidateCode;
import com.alibaba.fastjson.JSON;
import com.qf.domain.Address;
import com.qf.domain.User;
import com.qf.service.AddressService;
import com.qf.service.UserService;
import com.qf.service.impl.AddressServiceImpl;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.Base64Utils;
import com.qf.utils.RandomUtils;
import com.qf.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@WebServlet("/userservlet")
public class UserServlet extends BaseServlet {
    //当走UserServlet 会走doget 都post 自己没有就会走父类的BaseServlet ，base重写了所以走baseservlet的
    //所以只需user中写方法就可
//    @Override
//    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        //这些优化其实是SpringMVC差不多
//        String methodName = request.getParameter("method");
//        if (methodName.equals("register")) {
//            //注册
//            //register();
//        }else if(methodName.equals("login")){
//            //登录
//            //login();
//        }
//        //违背开闭原则，反射获取方法(之后添加方法不用if-else了)
//        try {
//            Method method=this.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);//后边这俩是形参，按照顺序写好
//            if (method != null) {
//                method.invoke(this,request,response);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//   }

//    @Override
//    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        this.doGet(request, response);
//    }



/*注册*/
    public String  register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
          //加这些参数是因为不管登录还是注册还是什么都需要 request response 取请求响应

//        System.out.println("注册成功");
//        //转发
//        //return "/index.jsp";
//        //重定向
//        return "redirect:/index.jsp";
       // return null;//json


        //获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");
        //校验
        if(StringUtils.isEmpty(username)){
            request.setAttribute("msg","用户名不能为空");
            return "/register.jsp";
        }
        if(StringUtils.isEmpty(password)){
            request.setAttribute("msg","密码不能为空");
            return "/register.jsp";
        }
        if(!password.equalsIgnoreCase(repassword)){  //注意是！
            request.setAttribute("msg","两次输入密码不一致");
            return "/register.jsp";
        }
        //性别是checked选择的所以不用验证
        if(StringUtils.isEmpty(email)){
            request.setAttribute("msg","邮箱不能为空");
            return "/register.jsp";
        }
        //调用业务逻辑
        UserService userService = new UserServiceImpl();
        boolean b = userService.checkUserName(username);
        if (b) {//true 表已存在，不可注册
            request.setAttribute("msg","用户名已存在");
            return "/register.jsp";
        }

        //友情提示：邮箱激活扩展内容 如果不写邮箱激活功能 flag=1因为没激活的登录不进去（激活过程其实是0->1的过程）
        //flag 0未激活 1激活 2 无效  role 0管理员 1会员
        User user = new User(0,username,password,email,gender,0,1, RandomUtils.createActiveCode());
        try {
            userService.register(user);
            //转发重定向
            return "redirect:/registerSuccess.jsp";
        } catch (Exception e) {
            e.printStackTrace();//跟踪错误信息，看控制台报错才能知道哪错了
            request.setAttribute("msg","注册失败");
            return "/register.jsp";
        }

    }
    public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //1获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("vcode");

        //后加 自动登录
        String auto = request.getParameter("auto");



        //校验
        if(StringUtils.isEmpty(username)){
            request.setAttribute("msg","用户名不能为空");
            return "/message.jsp";
        }
        if(StringUtils.isEmpty(password)){
            request.setAttribute("msg","密码不能为空");
            return "/message.jsp";
        }
        if(StringUtils.isEmpty(vcode)){
            request.setAttribute("msg","验证码不能为空");
            return "/message.jsp";
        }
        //校验验证码
        String code = (String)request.getSession().getAttribute("vcode");
        if(!vcode.equalsIgnoreCase(code)){
            request.setAttribute("msg","验证码错误");
            return "/message.jsp";
        }

        try {
            //调用业务逻辑
            UserService userService = new UserServiceImpl();
            User user = userService.login(username,password);
            //把用户存入session中
            request.getSession().setAttribute("user",user);

            //后加自动登录功能
            System.out.println(auto);//勾选 on 不勾选null
            if (auto!=null) {
                //自动登录
                String userInfo = username+"#"+password;//bbb#123456
                //Base64处理
                userInfo= Base64Utils.encode(userInfo);
                Cookie cookie=new Cookie("userInfo",userInfo);
                //设置路径
                cookie.setPath(request.getContextPath());
                //有效日期
                cookie.setMaxAge(14*24*60*60);//两周自动登录
                //设置 http协议才能访问
                cookie.setHttpOnly(true);
                //回写
                response.addCookie(cookie);
            }


            //3转发重定向
            return "redirect:/index.jsp";
            //return null;//没想好转发还是重定向返回null 即可
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","用户登录失败："+e.getMessage());
            return "/message.jsp";
        }
    }


    /*获取验证码功能*/
    public String code(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        response.setHeader("Pragma","no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", -1); //以上是先清除缓存 就这三句话  首先通过设置HTTP响应头（Pragma, Cache-Control, Expires）来确保验证码图片每次请求时都会从服务器获取新的，而不是使用缓存中的旧图片。
        //1创建验证码对象
        ValidateCode validateCode = new ValidateCode(100,28,4,20);
        //2验证码存入session中
        request.getSession().setAttribute("vcode",validateCode.getCode());
        System.out.println(validateCode.getCode());
        //响应给浏览器
        validateCode.write(response.getOutputStream());
        return null;
    }

    /*
    * 验证用户名是否存在*/
    public String checkUserName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String username = request.getParameter("username");
        System.out.println("username = " + username);
        if(StringUtils.isEmpty(username)){
            response.getWriter().write("1");//1表示不可用
            return null;//null 表示既不转发也不重定向  做完响应return结束，不然后边代码还得走受到影响
        }
        UserService userService = new UserServiceImpl();
        boolean b=userService.checkUserName(username);
        if(b){//b=true 已存在，不可用，写个1，每次昨晚处理
            response.getWriter().write("1");////null 表示既不转发也不重定向  做完响应return结束，不然后边代码还得走受到影响
            return null;
        }
        response.getWriter().write("0"); //0用户不存在，可以使用（用户不存在才可以注册）
        return null;
    }

    /*退出功能*/
    public String logOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //1把session中的信息移除
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        //2session失效
        session.invalidate();
        //3删除自动登录Cookie
        Cookie cookie=new Cookie("userInfo","");
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        //4重定向
        return "redirect:/index.jsp";
    }
    /*--------------------------------------------------------------以上是用户模块-----------------------------------------------------------*/
    /*-------------------------------------------------------------------------------------------------------------------------------------*/
    /*-------------------------------------------------------------以下是地址模块------------------------------------------------------------*/


    /*新增地址*/
    //http://localhost:8080/userservlet?method=addAddress
    public String addAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //判断用户是否登录  登录了才能得到用户id
        User user = (User)request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //获取前端数据
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        //非空验证
        if (StringUtils.isEmpty(name)) {
            request.setAttribute("msg","收货人姓名不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(phone)) {
            request.setAttribute("msg","收货人电话不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(detail)) {
            request.setAttribute("msg","收货人详细地址不能为空");
            return "/message.jsp";
        }
        try {
            //调用业务逻辑
            AddressService addressService = new AddressServiceImpl();
            Address address = new Address(0,detail,name,phone,user.getId(),0);//主键自增写个0就可以了
            addressService.add(address);
                 //之后每次添加完之后都要看一下是不是修改成功  查看一下地址
            return "redirect:userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","添加地址失败"+e.getMessage());
            return "/message.jsp";
        }
    }

    /*查询地址*/
    //userservlet?method=getAddress
    public String getAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1判断用户是否登录  登录了才能得到用户id
        User user = (User)request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        try {
            //2.调用业务逻辑
            AddressService addressService = new AddressServiceImpl();
            List<Address> addList = addressService.find(user.getId());//谁登录地址就是谁的，通过用户id找地址，能找到一堆地址
            //存储
            request.setAttribute("addList",addList);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","查询地址失败"+e.getMessage());
            return "/message.jsp";
        }
        return "/address_info.jsp";
    }
    //  //userservlet?method=deleteAddress&id=8
    public String deleteAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1判断用户是否登录  登录了才能得到用户id
        User user = (User)request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //获取前端数据
        String id = request.getParameter("id");//自己可以加上非空验证
        //非空验证
        try {
            //调用业务逻辑
            AddressService addressService = new AddressServiceImpl();
            addressService.remove(user.getId(),Integer.parseInt(id));//某个用户的某个地址，其实只传地址id也可也是唯一的
            return "redirect:userservlet?method=getAddress";//实际使用的时候也是不论是新增修改还是删除，成功了都要先查看一下是吧
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","删除地址失败"+e.getMessage());
            return "/message.jsp";
        }
    }
    //设置默认地址
    //http://localhost:8080/userservlet?method=defaultAddress&id=7
    public String defaultAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1判断用户是否登录  登录了才能得到用户id
        User user = (User)request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //接收前端数据
        String id = request.getParameter("id");
        //非空验证
        try {
            //调用业务逻辑
            AddressService addressService = new AddressServiceImpl();
            addressService.updatelevel(user.getId(),Integer.parseInt(id));
            return "redirect:userservlet?method=getAddress";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            request.setAttribute("msg","设置默认地址失败"+e.getMessage());
            return "/message.jsp";
        }
    }
    /*更新修改地址*/
    //userservlet?method=updateAddress
    public String updateAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1判断用户是否登录  登录了才能得到用户id
        User user = (User)request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //接受前端数据  //添加没有id但是更新有id  //前端代码显示在隐藏域中
        String id = request.getParameter("id");
        String level = request.getParameter("level");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        //非空验证
        //非空验证
        if (StringUtils.isEmpty(id)) {
            request.setAttribute("msg","地址编号不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(name)) {
            request.setAttribute("msg","收货人姓名不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(phone)) {
            request.setAttribute("msg","收货人电话不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(detail)) {
            request.setAttribute("msg","收货人详细地址不能为空");
            return "/message.jsp";
        }
        try {
            //调用业务逻辑
            AddressService addressService = new AddressServiceImpl();
            Address address = new Address(Integer.parseInt(id),detail,name,phone,user.getId(),Integer.parseInt(level));
            addressService.update(address);
            return "redirect:userservlet?method=getAddress";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            request.setAttribute("msg", "更新地址失败" + e.getMessage());
            return "/message.jsp";
        }
    }

    /*--------------------------------------------------------------以上是地址模块-----------------------------------------------------------*/
    /*-------------------------------------------------------------------------------------------------------------------------------------*/
    /*-------------------------------------------------------------以下是管理员模块----------------------------------------------------------*/
    ///userservlet?method=adminLogin
    public String adminLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //校验
        if(StringUtils.isEmpty(username)){
            request.setAttribute("msg","用户名不能为空");
            return "/message.jsp";
        }
        if(StringUtils.isEmpty(password)){
            request.setAttribute("msg","密码不能为空");
            return "/message.jsp";
        }


        try {
            //调用业务逻辑
            UserService userService = new UserServiceImpl();
            User admin = userService.adminLogin(username,password);
             //把用户存入session中
            request.getSession().setAttribute("admin",admin);
            //3转发重定向
            return "redirect:/admin/admin.jsp";
            //return null;//没想好转发还是重定向返回null 即可
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","管理员登录失败："+e.getMessage());
            return "/message.jsp";
        }
    }
    public String listUser(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        response.setContentType("text/html;charset = UTF-8");
        UserService userService=new UserServiceImpl();
        List<User> users= userService.slectAll();
        String jsonString = JSON.toJSONString(users);
        response.getWriter().write(jsonString);
        return null;
    }
    public String deleteUser(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        String uid = request.getParameter("id");
        UserService userService=new UserServiceImpl();
        userService.deleteById(uid);
        return "redirect:/admin/admin.jsp";
    }
    public String searchUser(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        String username = request.getParameter("username");
        String gender = request.getParameter("gender");
        StringBuilder where1=new StringBuilder(" where 1=1 ");
        List<String> I=new ArrayList();
        if (username!=null&&username!="")
        {
            where1.append(" and username like ? ");
            I.add("%"+username+"%");
        }
        if (gender!=null&&gender!="")
        {
            where1.append(" and gender = ? ");
            I.add(gender);
        }

        UserService userService=new UserServiceImpl();
        List<User> users = userService.selectByUAG(where1, I);
        response.getWriter().write(JSON.toJSONString(users));
        return null;
    }
    public String listljUser(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        response.setContentType("text/html;charset = UTF-8");
        UserService userService=new UserServiceImpl();
        List<User> users= userService.slectAll();
        List<User> newusers =new ArrayList<>();
        for (User user : users) {
            if (user.getFlag() == 2) {
                newusers.add(user);
            }
        }
        String jsonString = JSON.toJSONString(newusers);
        response.getWriter().write(jsonString);
        return null;
    }
    public String searchljUser (HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        String username = request.getParameter("username");
        String gender = request.getParameter("gender");
        StringBuilder where1=new StringBuilder(" where 1=1 ");
        List<String> I=new ArrayList();
        if (username!=null&&username!="")
        {
            where1.append(" and username like ? ");
            I.add("%"+username+"%");
        }
        if (gender!=null&&gender!="")
        {
            where1.append(" and gender = ? ");
            I.add(gender);
        }

        UserService userService=new UserServiceImpl();
        List<User> users = userService.selectByUAG(where1, I);
        List<User> newusers =new ArrayList<>();
        for (User user : users) {
            if (user.getFlag() == 2) {
                newusers.add(user);
            }
        }

        response.getWriter().write(JSON.toJSONString(newusers));
        return null;
    }
    public String adminLogOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

        HttpSession session = request.getSession();
        session.removeAttribute("admin");

        session.invalidate();
        return "redirect:/admin/login.jsp";
    }
}


